// pages/index/addressSelect/addressSelect.js
var city = require('../../utils/city.js');
const app = getApp()

Page({
  data: {
    show: true,
    isIpx: app.globalData.isIphoneX ? true : false,
    closeImg: 'https://gitee.com/Anjina/vote-pic/raw/7b66d388a031fdd545ce9a4ffc6a31e74de6710c/assets/Combined%20Shape@2x.png',
    buttonRawOne: {},
    positionLogo: 'https://gitee.com/Anjina/vote-pic/raw/7b66d388a031fdd545ce9a4ffc6a31e74de6710c/assets/%E5%AE%9A%E4%BD%8D@2x.png',
    searchLetter: [],
    showLetter: "",
    winHeight: 0,
    cityList: [],
    isShowLetter: false,
    currentCity: "",
    toView: 'inToViewA', 
    result: [],
    searching: false,
    inputVal:'',
    isInput: false
  },
  getVal: function (e) {
    var val = e.detail.value;
    var result = [];
    var that = this;
    for(var i=0;i<15;i++){
      for (var j = 0; j < this.data.cityList[i].cityInfo.length;j++){
        
          if (this.data.cityList[i].cityInfo[j].city.search(val) != -1){
            result.push(this.data.cityList[i].cityInfo[j].city);
        }
      }
    }
    if(val === ''){
      result = [],
      that.setData({
        searching: false,
        show: true,
        isInput: false
      })
    }
    else{
      that.setData({
        searching: true,
        show: false,
        inputVal:val,
        isInput: true
      })
    }
    console.log(val)
    that.setData({
      result: result,
    })
  },
  handleFocus: function(){
    this.setData({
      isInput: true
    })
  },
  handleBlur: function(){
    this.setData({
      isInput: false
    })
  },
  clear: function (){
    console.log(this.data.inputVal)
    console.log('s')
    this.setData({
      inputVal: '',
      show: true,
      isInput: false
    })
  },
  toSearch: function () {
   // this.data.cityList[0].cityInfo[0].city.length
    console.log(this.data.result)
    console.log(this.data.searching)
  },
  loadInfo: function () {
    var page = this
    wx.getLocation({
      type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标 
      success: function (res) {
        // success 
        var longitude = res.longitude
        var latitude = res.latitude
        page.loadCity(longitude, latitude)
      },
      fail: function () {
        // fail 
      },
      complete: function () {
        // complete 
      }
    })
  },

  loadCity: function (longitude, latitude) {
    var page = this
    wx.request({
      url: 'https://api.map.baidu.com/geocoder/v2/?ak=gF4MmG52pgBKAzx6xwgr1eSMeHLUhd19&location=' + latitude + ',' + longitude + '&output=json&pois=1',
      //这里的ak 是去百度地图api获取的需要自己登陆获取一下 地址：https://lbsyun.baidu.com/index.php?title=wxjsapi
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        // success 
        console.log(res);
        var city = res.data.result.addressComponent.city;
        var sub1 = city.substring(city.length - 1, city.length);
        if (sub1 = '市') {
          city = city.substring(0, city.length - 1);
        }
        var currentCity = page.data.currentCity;
        console.log(page.data.currentCity)
        currentCity = city
        page.setData({ currentCity: currentCity });
        var pages = getCurrentPages();
        var prevPage = pages[pages.length-2];
        var item = prevPage.data.item;
        var str1 = 'item.city_isClicked';
        var str2 = 'item.country_isClicked';
        item.currentCity = city;
        item.defaultVal = city;
        item.userLocation = true
        item.lineWidth = (city.length + 1) * 30 - 4 + 'rpx'
        item.marginLeft = 490 + 'rpx'
        console.log(item.marginLeft)
        prevPage.setData({
          item: item,
          [str1]: true,
          [str2]: false
        })
      },
      fail: function () {
        // fail 
      },
      complete: function () {
        // complete 
      }
    })
  },
  onLoad: function (options) {
    // 生命周期函数--监听页面加载
    var that = this
    wx.request({
      url: 'https://m.feawin.com/vote/hot/city?activityId=1',
      success(res) {
        that.setData({
          buttonRawOne: res.data.list
        })
      }
    })
    var defaultVal = options.defaultVal
    if(defaultVal){
      that.setData({
        currentCity: defaultVal
      })
    }
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
            success: function (res) {
              if (res.cancel) {
                that.setData({
                  isshowCIty: false
                })
                wx.showToast({
                  title: '授权失败',
                  icon: 'success',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用getLocationt的API
                      that.loadInfo()
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } 
      }
    })
    var searchLetter = city.searchLetter;
    var cityList = city.cityList();

    var sysInfo = wx.getSystemInfoSync();
    //console.log(sysInfo);
    var winHeight = sysInfo.windowHeight;  //可使用窗口高度

    //添加要匹配的字母范围值
    //1、更加屏幕高度设置子元素的高度
    var itemH = winHeight / searchLetter.length;
    var tempObj = [];
    for (var i = 0; i < searchLetter.length; i++) {
      var temp = {};
      temp.name = searchLetter[i];
      tempObj.push(temp)
    }
   // console.log(tempObj)

    this.setData({
      winHeight: winHeight,
      searchLetter: tempObj,
      cityList: cityList
    })
  },
  scrollToViewFn: function (e) {
    var _id = e.target.dataset.letter;
    this.setData({
      toView: 'inToView' + _id
    })
    //console.log(this.data.toView)
    //console.log(e.target.dataset)
  }, 
  bindCity: function (e) {
    var city = e.currentTarget.dataset.city;
    this.setData({ currentCity: city });
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    var item = prevPage.data.item;
    item.currentCity = city;
    item.defaultVal = city;
    switch(item.page){
      case 'Article':
        app.globalData.articleCity = city
        break
      case 'Pic':
        app.globalData.picCity = city
        break
      case 'Video':
        app.globalData.videoCity = city
        break
      default:
        console.log('error')
    }
    item.lineWidth = (city.length + 1) * 30 - 4 + 'rpx';
    item.marginLeft = 490 + 'rpx'
    var str1 = 'item.city_isClicked';
    var str2 = 'item.country_isClicked';
    prevPage.setData({
      item: item,
      [str1]: true,
      [str2]: false
    })
    wx.navigateBack({
      delta: 1
    })
  },
})